from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import status
from .models import Building, Floor, Park, Unit, Device, Vehicle
from services.models import Contract, DeviceMaintenance
from django.db.models import Count, Q, F, Sum
from django.core.paginator import Paginator
from django.utils import timezone
from decimal import Decimal
import random
from rest_framework.permissions import IsAuthenticated
from users.models import User, CompanyEmployeeProfile, ParkEmployeeProfile, Visitor

# Create your views here.

# 楼宇管理相关视图函数

@api_view(['GET', 'POST'])
def building_list(request):
    """
    获取所有楼宇列表或创建新楼宇
    """
    if request.method == 'GET':
        name = request.query_params.get('name', None)
        page = int(request.query_params.get('current', 1))
        size = int(request.query_params.get('size', 10))
        
        queryset = Building.objects.select_related('park').all()
        
        if name:
            queryset = queryset.filter(name__icontains=name)
            
        paginator = Paginator(queryset.order_by('-created_at'), size)
        buildings_page = paginator.get_page(page)
        
        buildings = []
        for building in buildings_page:
            buildings.append({
                'building_id': building.building_id,
                'name': building.name,
                'total_floors': building.total_floors,
                'building_area': str(building.building_area) if building.building_area else '0.00',
                'completion_date': building.completion_date,
                'building_type': building.building_type,
                'park': {
                    'park_id': building.park.park_id,
                    'name': building.park.name
                },
                'created_at': building.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'updated_at': building.updated_at.strftime('%Y-%m-%d %H:%M:%S')
            })
        
        return Response({
            'code': 200,
            'message': '获取楼宇列表成功',
            'data': {
                'total': paginator.count,
                'list': buildings
            }
        })
    
    elif request.method == 'POST':
        data = request.data
        try:
            park = Park.objects.get(pk=data.get('park'))
            
            Building.objects.create(
                park=park,
                name=data.get('name'),
                total_floors=data.get('total_floors'),
                building_area=Decimal(data.get('building_area')) if data.get('building_area') else None,
                completion_date=data.get('completion_date'),
                building_type=data.get('building_type'),
                structure_type=data.get('structure_type'),
                fire_rating=data.get('fire_rating'),
            )
            
            return Response({'code': 201, 'message': '添加楼宇成功'}, status=status.HTTP_201_CREATED)
        except Park.DoesNotExist:
            return Response({'code': 400, 'message': '园区不存在'}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'code': 500, 'message': f'添加楼宇失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET', 'PUT', 'DELETE'])
def building_detail(request, pk):
    """
    获取、更新或删除单个楼宇
    """
    try:
        building = Building.objects.select_related('park').get(building_id=pk)
    except Building.DoesNotExist:
        return Response({'code': 404, 'message': '楼宇不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    if request.method == 'GET':
        building_data = {
            'building_id': building.building_id,
            'name': building.name,
            'total_floors': building.total_floors,
            'building_area': str(building.building_area) if building.building_area else '0.00',
            'completion_date': building.completion_date,
            'building_type': building.building_type,
            'structure_type': building.structure_type,
            'fire_rating': building.fire_rating,
            'park': {
                'park_id': building.park.park_id,
                'name': building.park.name
            },
            'created_at': building.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': building.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }
        return Response({'code': 200, 'message': '获取楼宇详情成功', 'data': building_data})
    
    elif request.method == 'PUT':
        data = request.data
        try:
            building.name = data.get('name', building.name)
            building.total_floors = data.get('total_floors', building.total_floors)
            building.building_area = Decimal(data.get('building_area', building.building_area))
            building.completion_date = data.get('completion_date', building.completion_date)
            building.building_type = data.get('building_type', building.building_type)
            building.structure_type = data.get('structure_type', building.structure_type)
            building.fire_rating = data.get('fire_rating', building.fire_rating)
            building.save()
            return Response({'code': 200, 'message': '更新楼宇成功'})
        except Exception as e:
            return Response({'code': 500, 'message': f'更新楼宇失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    elif request.method == 'DELETE':
        building.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

@api_view(['GET'])
def building_floors(request, pk):
    """
    获取指定楼宇的所有楼层, 并附带统计信息
    """
    if not Building.objects.filter(building_id=pk).exists():
        return Response({'code': 404, 'message': '楼宇不存在'}, status=status.HTTP_404_NOT_FOUND)

    floors_qs = Floor.objects.filter(building_id=pk).annotate(
        roomCount=Count('unit'),
        rentedCount=Count('unit', filter=Q(unit__status='已租'))
    ).order_by('floor_number')

    floors_data = []
    for floor in floors_qs:
        total_area = Unit.objects.filter(floor=floor).aggregate(total=Sum('actual_area'))['total'] or Decimal('0.00')
        floors_data.append({
            'id': floor.floor_id,
            'floorNumber': floor.floor_number,
            'area': str(total_area),
            'roomCount': floor.roomCount,
            'rentedCount': floor.rentedCount,
            'rentRate': int(floor.rentedCount / floor.roomCount * 100) if floor.roomCount > 0 else 0,
            'usage': floor.function_zone_desc
        })
        
    return Response({'code': 200, 'message': '获取楼层列表成功', 'data': floors_data})

@api_view(['GET'])
def building_devices(request, pk):
    """
    获取指定楼宇的所有设备
    """
    if not Building.objects.filter(building_id=pk).exists():
        return Response({'code': 404, 'message': '楼宇不存在'}, status=status.HTTP_404_NOT_FOUND)
        
    devices_qs = Device.objects.filter(building_id=pk).order_by('-created_at')
    
    # Simple pagination for safety
    paginator = Paginator(devices_qs, 100) # Assuming max 100 devices shown on this page
    devices_page = paginator.get_page(1)

    devices_data = []
    for device in devices_page:
        devices_data.append({
            'id': device.device_id,
            'name': device.device_name,
            'type': device.device_type,
            'status': device.status,
            'location': device.location_desc or f"{device.floor.floor_number}层" if device.floor else "公共区域",
        })
        
    return Response({'code': 200, 'message': '获取设备列表成功', 'data': devices_data})

@api_view(['GET', 'PUT'])
def floor_detail(request, pk):
    """
    获取或更新单个楼层
    """
    try:
        floor = Floor.objects.select_related('building', 'building__park').get(floor_id=pk)
    except Floor.DoesNotExist:
        return Response({'code': 404, 'message': '楼层不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    if request.method == 'GET':
        floor_data = {
            'floor_id': floor.floor_id,
            'floor_number': floor.floor_number,
            'actual_label': floor.actual_label,
            'height': str(floor.height) if floor.height else '0.00',
            'load_bearing': str(floor.load_bearing) if floor.load_bearing else '0.00',
            'function_zone_desc': floor.function_zone_desc,
            'building': {
                'building_id': floor.building.building_id,
                'name': floor.building.name
            },
            'created_at': floor.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': floor.updated_at.strftime('%Y-%m-%d %H:%M:%S'),
        }
        return Response({'code': 200, 'message': '获取楼层详情成功', 'data': floor_data})

    elif request.method == 'PUT':
        data = request.data
        try:
            floor.actual_label = data.get('actual_label', floor.actual_label)
            floor.height = Decimal(data.get('height', floor.height))
            floor.load_bearing = Decimal(data.get('load_bearing', floor.load_bearing))
            floor.function_zone_desc = data.get('function_zone_desc', floor.function_zone_desc)
            floor.save()
            return Response({'code': 200, 'message': '更新楼层成功'})
        except Exception as e:
            return Response({'code': 500, 'message': f'更新楼层失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
def floor_rooms(request, pk):
    """
    获取指定楼层的所有房间/单元
    """
    if not Floor.objects.filter(floor_id=pk).exists():
        return Response({'code': 404, 'message': '楼层不存在'}, status=status.HTTP_404_NOT_FOUND)
        
    rooms_qs = Unit.objects.filter(floor_id=pk).order_by('unit_number')
    
    rooms_data = []
    for room in rooms_qs:
        # 查找与该房间关联合同的最新租户公司名
        contract = Contract.objects.filter(unit=room, status='生效中').select_related('company').order_by('-sign_date').first()
        company_name = contract.company.company_name if contract and contract.company else ''

        rooms_data.append({
            'id': room.unit_id,
            'roomNumber': f"{room.building.building_type}{room.unit_number.split('-')[-1]}",
            'area': str(room.actual_area) if room.actual_area else '0.00',
            'type': room.unit_type,
            'status': room.status,
            'company': company_name,
        })
        
    return Response({'code': 200, 'message': '获取房间列表成功', 'data': rooms_data})

@api_view(['GET'])
def floor_public_devices(request, pk):
    """
    获取指定楼层的公共设备 (即没有关联到具体房间的设备)
    """
    if not Floor.objects.filter(floor_id=pk).exists():
        return Response({'code': 404, 'message': '楼层不存在'}, status=status.HTTP_404_NOT_FOUND)
        
    devices_qs = Device.objects.filter(floor_id=pk, unit__isnull=True).order_by('device_name')

    devices_data = []
    for device in devices_qs:
        devices_data.append({
            'id': device.device_id,
            'name': device.device_name,
            'count': 1, # 列表页通常只关心种类和状态，可简化
            'status': device.status,
        })
        
    return Response({'code': 200, 'message': '获取楼层公共设备列表成功', 'data': devices_data})

@api_view(['GET', 'PUT'])
def unit_detail(request, pk):
    """
    获取或更新单个单元/房间
    """
    try:
        unit = Unit.objects.select_related('floor', 'building').get(unit_id=pk)
    except Unit.DoesNotExist:
        return Response({'code': 404, 'message': '房间不存在'}, status=status.HTTP_404_NOT_FOUND)
        
    if request.method == 'GET':
        import json
        media_urls = []
        if unit.media_urls:
            try:
                urls = json.loads(unit.media_urls)
                media_urls = [{'url': url} for url in urls]
            except json.JSONDecodeError:
                media_urls = []

        unit_data = {
            'unit_id': unit.unit_id,
            'unit_number': unit.unit_number,
            'actual_area': str(unit.actual_area) if unit.actual_area else '0.00',
            'building_area': str(unit.building_area) if unit.building_area else '0.00',
            'unit_type': unit.unit_type,
            'status': unit.status,
            'rental_price': str(unit.rental_price) if unit.rental_price else '0.00',
            'sale_price': str(unit.sale_price) if unit.sale_price else '0.00',
            'property_fee_standard': str(unit.property_fee_standard) if unit.property_fee_standard else '0.00',
            'orientation': unit.orientation,
            'facilities_desc': unit.facilities_desc,
            'media_urls': media_urls,
            'floor': {
                'floor_id': unit.floor.floor_id,
                'floor_number': unit.floor.floor_number,
            },
            'building': {
                'building_id': unit.building.building_id,
                'name': unit.building.name,
            },
            'created_at': unit.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': unit.updated_at.strftime('%Y-%m-%d %H:%M:%S'),
        }
        return Response({'code': 200, 'message': '获取房间详情成功', 'data': unit_data})

    elif request.method == 'PUT':
        # ... (PUT logic can be added here later if needed)
        pass

@api_view(['GET'])
def unit_devices(request, pk):
    """
    获取指定单元/房间的所有设备
    """
    if not Unit.objects.filter(unit_id=pk).exists():
        return Response({'code': 404, 'message': '房间不存在'}, status=status.HTTP_404_NOT_FOUND)
        
    devices_qs = Device.objects.filter(unit_id=pk).order_by('device_name')

    devices_data = []
    for device in devices_qs:
        devices_data.append({
            'device_id': device.device_id,
            'device_name': device.device_name,
            'device_type': device.device_type,
            'status': device.status,
        })
        
    return Response({'code': 200, 'message': '获取房间设备列表成功', 'data': devices_data})

@api_view(['GET'])
def unit_contract(request, pk):
    """
    获取指定单元/房间的当前生效合同
    """
    if not Unit.objects.filter(unit_id=pk).exists():
        return Response({'code': 404, 'message': '房间不存在'}, status=status.HTTP_404_NOT_FOUND)
        
    contract = Contract.objects.filter(unit_id=pk, status='生效中').select_related('company', 'user').order_by('-sign_date').first()
    
    if not contract:
        return Response({'code': 404, 'message': '未找到生效的合同', 'data': None}, status=status.HTTP_200_OK)

    # 根据新的字段含义:
    # - party_b 字段表示"甲方主体"（出租方/园区）
    # - company_id/user_id 字段表示"乙方"（承租方/企业或个人）
    tenant_name = contract.company.company_name if contract.company else (_get_user_real_name(contract.user) if contract.user else '')
    tenant_phone = contract.company.contact_phone if contract.company else (contract.user.phone if contract.user else '')

    contract_data = {
        'contract_number': contract.contract_number,
        'tenant_name': tenant_name,
        'tenant_phone': tenant_phone,
        'start_date': contract.start_date,
        'end_date': contract.end_date,
        'status': contract.status,
    }

    return Response({'code': 200, 'message': '获取合同信息成功', 'data': contract_data})

# 设备管理
@api_view(['GET', 'POST'])
def device_list(request):
    """
    获取所有设备列表或创建新设备
    """
    if request.method == 'GET':
        # 1. 获取查询参数
        page = int(request.query_params.get('current', 1))
        size = int(request.query_params.get('size', 10))
        building_id = request.query_params.get('building_id')
        floor_id = request.query_params.get('floor_id')
        unit_id = request.query_params.get('unit_id')
        device_type = request.query_params.get('device_type')
        status_param = request.query_params.get('status')
        ordering = request.query_params.get('ordering')

        # 2. 构建查询集
        queryset = Device.objects.select_related(
            'building', 'floor', 'unit'
        ).all()

        # 3. 应用筛选条件
        if building_id:
            queryset = queryset.filter(building_id=building_id)
        if floor_id:
            queryset = queryset.filter(floor_id=floor_id)
        if unit_id:
            queryset = queryset.filter(unit_id=unit_id)
        if device_type:
            queryset = queryset.filter(device_type__icontains=device_type)
        if status_param:
            queryset = queryset.filter(status=status_param)

        # 4. 应用排序
        if ordering:
            queryset = queryset.order_by(ordering)
        else:
            queryset = queryset.order_by('-created_at') # 默认排序

        # 5. 分页
        paginator = Paginator(queryset, size)
        devices_page = paginator.get_page(page)

        devices = []
        for device in devices_page:
            location_parts = []
            if device.building:
                location_parts.append(device.building.name)
            if device.floor:
                location_parts.append(f"{device.floor.floor_number}层")
            if device.unit:
                # 只截取单元编号的最后一部分, e.g., from 'BG1-101' to '101'
                unit_display_number = device.unit.unit_number.split('-')[-1]
                location_parts.append(unit_display_number)
            
            # 如果有关联的空间信息，则动态生成位置描述；否则，使用数据库中记录的描述
            location_display = " - ".join(location_parts) if location_parts else device.location_desc

            devices.append({
                'device_id': device.device_id,
                'device_name': device.device_name,
                'device_number': device.device_number,
                'device_type': device.device_type,
                'brand_model': device.brand_model,
                'location_desc': location_display,
                'status': device.status,
                'purchase_date': device.purchase_date,
                'last_maintenance_date': device.last_maintenance_date,
                'building': {'building_id': device.building.building_id, 'name': device.building.name} if device.building else None,
                'floor': {'floor_id': device.floor.floor_id, 'floor_number': device.floor.floor_number} if device.floor else None,
                'unit': {'unit_id': device.unit.unit_id, 'unit_number': device.unit.unit_number} if device.unit else None,
                'warranty_end_date': device.warranty_end_date,
                'maintenance_cycle': device.maintenance_cycle
            })
        
        return Response({
            'code': 200,
            'message': '获取设备列表成功',
            'data': {
                'total': paginator.count,
                'list': devices
            }
        })

    elif request.method == 'POST':
        data = request.data
        try:
            building = get_object_or_404(Building, pk=data.get('building_id'))
            floor = get_object_or_404(Floor, pk=data.get('floor_id')) if data.get('floor_id') else None
            unit = get_object_or_404(Unit, pk=data.get('unit_id')) if data.get('unit_id') else None
            
            # 自动生成设备名称、编号和位置
            device_type = data.get('device_type')
            device_name = f"{unit.unit_number} {device_type}" if unit else device_type
            device_number = f"D-{building.building_id}-{floor.floor_id if floor else 0}-{unit.unit_id if unit else 0}-{random.randint(1000, 9999)}"
            
            location_parts = []
            if building: location_parts.append(building.name)
            if floor: location_parts.append(f"{floor.floor_number}层")
            if unit: location_parts.append(unit.unit_number)
            location_desc = " - ".join(location_parts) if location_parts else data.get('location_desc', '')

            now = timezone.now()
            Device.objects.create(
                building=building,
                floor=floor,
                unit=unit,
                device_name=device_name,
                device_number=device_number,
                device_type=device_type,
                location_desc=location_desc,
                brand_model=data.get('brand_model'),
                purchase_date=data.get('purchase_date') if data.get('purchase_date') else None,
                warranty_end_date=data.get('warranty_end_date') if data.get('warranty_end_date') else None,
                status=data.get('status'),
                last_maintenance_date=data.get('last_maintenance_date') if data.get('last_maintenance_date') else None,
                maintenance_cycle=data.get('maintenance_cycle'),
                created_at=now,
                updated_at=now
            )
            return Response({'code': 201, 'message': '添加设备成功'}, status=status.HTTP_201_CREATED)
        except Exception as e:
            return Response({'code': 500, 'message': f'添加设备失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET', 'PUT', 'DELETE'])
def device_detail(request, pk):
    """
    获取、更新或删除单个设备
    """
    try:
        device = Device.objects.select_related('building', 'floor', 'unit').get(device_id=pk)
    except Device.DoesNotExist:
        return Response({'code': 404, 'message': '设备不存在'}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        # 获取关联的维保记录
        maintenance_records_qs = DeviceMaintenance.objects.filter(device=device).order_by('-maintenance_date')
        
        serialized_records = []
        for record in maintenance_records_qs:
            serialized_records.append({
                'maintenance_id': record.maintenance_id,
                'maintenance_type': record.maintenance_type,
                'content': record.content,
                'responsible_person': record.responsible_person,
                'maintenance_date': record.maintenance_date,
                'cost': str(record.cost) if record.cost is not None else '0.00',
            })

        device_data = {
            'device_id': device.device_id,
            'device_name': device.device_name,
            'device_number': device.device_number,
            'device_type': device.device_type,
            'brand_model': device.brand_model,
            'location_desc': device.location_desc,
            'status': device.status,
            'purchase_date': device.purchase_date,
            'warranty_end_date': device.warranty_end_date,
            'last_maintenance_date': device.last_maintenance_date,
            'maintenance_cycle': device.maintenance_cycle,
            'building': {
                'building_id': device.building.building_id,
                'name': device.building.name
            } if device.building else None,
            'floor': {
                'floor_id': device.floor.floor_id,
                'floor_number': device.floor.floor_number
            } if device.floor else None,
            'unit': {
                'unit_id': device.unit.unit_id,
                'unit_number': device.unit.unit_number
            } if device.unit else None,
            'created_at': device.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': device.updated_at.strftime('%Y-%m-%d %H:%M:%S'),
            'maintenance_records': serialized_records, # 添加维保记录
        }
        return Response({'code': 200, 'message': '获取设备详情成功', 'data': device_data})
    
    elif request.method == 'PUT':
        data = request.data
        try:
            device = Device.objects.get(pk=pk)
            
            # 更新关联关系
            building = get_object_or_404(Building, pk=data.get('building_id')) if data.get('building_id') else device.building
            floor = get_object_or_404(Floor, pk=data.get('floor_id')) if data.get('floor_id') else device.floor
            unit = get_object_or_404(Unit, pk=data.get('unit_id')) if data.get('unit_id') else device.unit

            # 重新生成设备名称和位置描述
            device_type = data.get('device_type', device.device_type)
            device.device_name = f"{unit.unit_number} {device_type}" if unit else device_type

            location_parts = []
            if building: location_parts.append(building.name)
            if floor: location_parts.append(f"{floor.floor_number}层")
            if unit: location_parts.append(unit.unit_number)
            device.location_desc = " - ".join(location_parts)

            # 更新其他字段
            device.building = building
            device.floor = floor
            device.unit = unit
            device.device_type = device_type
            device.brand_model = data.get('brand_model', device.brand_model)
            device.purchase_date = data.get('purchase_date', device.purchase_date)
            device.warranty_end_date = data.get('warranty_end_date', device.warranty_end_date)
            device.status = data.get('status', device.status)
            device.last_maintenance_date = data.get('last_maintenance_date', device.last_maintenance_date)
            device.maintenance_cycle = data.get('maintenance_cycle', device.maintenance_cycle)
            device.updated_at = timezone.now()
            
            device.save()
            return Response({'code': 200, 'message': '更新设备成功'})
        except Device.DoesNotExist:
            return Response({'code': 404, 'message': '设备不存在'}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({'code': 500, 'message': f'更新设备失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    elif request.method == 'DELETE':
        try:
            device = Device.objects.get(pk=pk)
            device.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except Device.DoesNotExist:
            return Response({'code': 404, 'message': '设备不存在'}, status=status.HTTP_404_NOT_FOUND)

# 以下是被注释掉的API，可以根据需要取消注释并实现

# @api_view(['GET', 'POST'])
# def park_list(request):

# Dashboard统计接口
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def building_count(request):
    """获取建筑数量"""
    count = Building.objects.count()
    return Response({'count': count})

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def device_count(request):
    """获取设备数量"""
    count = Device.objects.count()
    return Response({'count': count})

@api_view(['GET', 'POST'])
def vehicle_list(request):
    """
    获取所有车辆列表或创建新车辆
    """
    if request.method == 'GET':
        plate_number = request.query_params.get('plate_number', None)
        owner_type = request.query_params.get('owner_type', None)
        vehicle_type = request.query_params.get('vehicle_type', None)
        page = int(request.query_params.get('page', 1))
        limit = int(request.query_params.get('limit', 10))
        
        # 使用select_related预加载关联数据，减少查询次数
        queryset = Vehicle.objects.select_related('user', 'visitor').prefetch_related('user__companyemployeeprofile')
        
        # 应用过滤条件
        if plate_number:
            queryset = queryset.filter(plate_number__icontains=plate_number)
        if vehicle_type:
            queryset = queryset.filter(vehicle_type=vehicle_type)
        if owner_type:
            if owner_type == 'employee':
                queryset = queryset.filter(user__isnull=False)
            elif owner_type == 'visitor':
                queryset = queryset.filter(visitor__isnull=False)
            
        paginator = Paginator(queryset.order_by('-created_at'), limit)
        vehicles_page = paginator.get_page(page)
        
        vehicles = []
        for vehicle in vehicles_page:
            vehicle_data = {
                'vehicle_id': vehicle.vehicle_id,
                'plate_number': vehicle.plate_number,
                'brand': vehicle.brand,
                'model': vehicle.model,
                'color': vehicle.color,
                'vehicle_type': vehicle.vehicle_type,
                'register_date': vehicle.register_date.strftime('%Y-%m-%d') if vehicle.register_date else None,
                'created_at': vehicle.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'updated_at': vehicle.updated_at.strftime('%Y-%m-%d %H:%M:%S')
            }
            
            # 根据所属类型添加用户或访客信息
            if vehicle.user:
                user = vehicle.user
                user_profile_name = None
                
                # 获取企业员工姓名
                try:
                    if hasattr(user, 'companyemployeeprofile'):
                        user_profile_name = user.companyemployeeprofile.name
                except:
                    pass
                
                vehicle_data['user'] = {
                    'user_id': user.user_id,
                    'username': user.username,
                    'name': user_profile_name or user.username,  # 优先使用档案中的姓名，没有则用用户名
                    'phone': user.phone
                }
                
                # 如果有公司员工档案，添加公司员工信息
                if hasattr(user, 'companyemployeeprofile'):
                    vehicle_data['user']['company_employee_profile'] = {
                        'company': {
                            'id': user.companyemployeeprofile.company.company_id,
                            'name': user.companyemployeeprofile.company.company_name
                        },
                        'department': user.companyemployeeprofile.department,
                        'position': user.companyemployeeprofile.position
                    }
            elif vehicle.visitor:
                visitor = vehicle.visitor
                vehicle_data['visitor'] = {
                    'visitor_id': visitor.visitor_id,
                    'name': visitor.name,
                    'phone': visitor.phone
                }
            
            vehicles.append(vehicle_data)
        
        return Response({
            'code': 200,
            'message': '获取车辆列表成功',
            'data': {
                'count': paginator.count,
                'results': vehicles
            }
        })
    
    elif request.method == 'POST':
        data = request.data
        try:
            # 检查必填字段
            if not data.get('plate_number') or not data.get('vehicle_type'):
                return Response({
                    'code': 400, 
                    'message': '车牌号和车辆类型为必填项'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 创建新车辆记录
            vehicle = Vehicle(
                plate_number=data.get('plate_number'),
                brand=data.get('brand'),
                model=data.get('model'),
                color=data.get('color'),
                vehicle_type=data.get('vehicle_type'),
                register_date=data.get('register_date') or timezone.now().date(),
                created_at=timezone.now(),
                updated_at=timezone.now()
            )
            
            # 设置所属用户或访客
            if data.get('user_id'):
                try:
                    user = User.objects.get(pk=data.get('user_id'))
                    vehicle.user = user
                except User.DoesNotExist:
                    return Response({'code': 400, 'message': '用户不存在'}, status=status.HTTP_400_BAD_REQUEST)
            elif data.get('visitor_id'):
                from users.models import Visitor
                try:
                    visitor = Visitor.objects.get(pk=data.get('visitor_id'))
                    vehicle.visitor = visitor
                except Visitor.DoesNotExist:
                    return Response({'code': 400, 'message': '访客不存在'}, status=status.HTTP_400_BAD_REQUEST)
            
            vehicle.save()
            
            return Response({'code': 201, 'message': '添加车辆成功'}, status=status.HTTP_201_CREATED)
        except Exception as e:
            return Response({'code': 500, 'message': f'添加车辆失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET', 'PUT', 'DELETE'])
def vehicle_detail(request, pk):
    """
    获取、更新或删除单个车辆信息
    """
    try:
        vehicle = Vehicle.objects.select_related('user', 'visitor').prefetch_related('user__companyemployeeprofile').get(vehicle_id=pk)
    except Vehicle.DoesNotExist:
        return Response({'code': 404, 'message': '车辆不存在'}, status=status.HTTP_404_NOT_FOUND)
    
    if request.method == 'GET':
        # 构建基本车辆信息
        vehicle_data = {
            'vehicle_id': vehicle.vehicle_id,
            'plate_number': vehicle.plate_number,
            'brand': vehicle.brand,
            'model': vehicle.model,
            'color': vehicle.color,
            'vehicle_type': vehicle.vehicle_type,
            'register_date': vehicle.register_date.strftime('%Y-%m-%d') if vehicle.register_date else None,
            'created_at': vehicle.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': vehicle.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }
        
        # 根据所属类型添加用户或访客信息
        if vehicle.user:
            user = vehicle.user
            user_profile_name = None
            
            # 获取企业员工姓名
            try:
                if hasattr(user, 'companyemployeeprofile'):
                    user_profile_name = user.companyemployeeprofile.name
            except:
                pass
                
            vehicle_data['user'] = {
                'user_id': user.user_id,
                'username': user.username,
                'name': user_profile_name or user.username,  # 优先使用档案中的姓名，没有则用用户名
                'phone': user.phone
            }
            
            # 如果有公司员工档案，添加公司员工信息
            if hasattr(user, 'companyemployeeprofile'):
                vehicle_data['user']['company_employee_profile'] = {
                    'company': {
                        'id': user.companyemployeeprofile.company.company_id,
                        'name': user.companyemployeeprofile.company.company_name
                    },
                    'department': user.companyemployeeprofile.department,
                    'position': user.companyemployeeprofile.position
                }
        elif vehicle.visitor:
            visitor = vehicle.visitor
            vehicle_data['visitor'] = {
                'visitor_id': visitor.visitor_id,
                'name': visitor.name,
                'phone': visitor.phone
            }
        
        return Response({'code': 200, 'message': '获取车辆详情成功', 'data': vehicle_data})
    
    elif request.method == 'PUT':
        data = request.data
        try:
            # 更新基本信息
            vehicle.plate_number = data.get('plate_number', vehicle.plate_number)
            vehicle.brand = data.get('brand', vehicle.brand)
            vehicle.model = data.get('model', vehicle.model)
            vehicle.color = data.get('color', vehicle.color)
            vehicle.vehicle_type = data.get('vehicle_type', vehicle.vehicle_type)
            if data.get('register_date'):
                vehicle.register_date = data.get('register_date')
            vehicle.updated_at = timezone.now()
            
            # 更新所属用户或访客
            if 'user_id' in data:
                if data.get('user_id') is not None:
                    try:
                        user = User.objects.get(pk=data.get('user_id'))
                        vehicle.user = user
                        vehicle.visitor = None  # 清除访客关联
                    except User.DoesNotExist:
                        return Response({'code': 400, 'message': '用户不存在'}, status=status.HTTP_400_BAD_REQUEST)
                    except Exception as e:
                        print(f"Error setting user: {str(e)}")  # 添加日志
                        return Response({'code': 500, 'message': f'设置用户关联失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                else:
                    vehicle.user = None
            
            if 'visitor_id' in data:
                if data.get('visitor_id') is not None:
                    from users.models import Visitor
                    try:
                        visitor = Visitor.objects.get(pk=data.get('visitor_id'))
                        vehicle.visitor = visitor
                        vehicle.user = None  # 清除用户关联
                    except Visitor.DoesNotExist:
                        return Response({'code': 400, 'message': '访客不存在'}, status=status.HTTP_400_BAD_REQUEST)
                    except Exception as e:
                        print(f"Error setting visitor: {str(e)}")  # 添加日志
                        return Response({'code': 500, 'message': f'设置访客关联失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                else:
                    vehicle.visitor = None
            
            vehicle.save()
            return Response({'code': 200, 'message': '更新车辆信息成功'})
        except Exception as e:
            import traceback
            print(f"Update vehicle error: {str(e)}")
            print(traceback.format_exc())  # 打印完整堆栈跟踪
            return Response({'code': 500, 'message': f'更新车辆信息失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    elif request.method == 'DELETE':
        try:
            vehicle.delete()
            return Response({'code': 204, 'message': '删除车辆信息成功'}, status=status.HTTP_204_NO_CONTENT)
        except Exception as e:
            return Response({'code': 500, 'message': f'删除车辆信息失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def my_vehicles(request):
    """
    获取当前登录用户的所有车辆列表
    """
    # 直接查询当前用户的车辆
    queryset = Vehicle.objects.filter(user=request.user).order_by('-created_at')
    
    # 使用分页
    page = int(request.query_params.get('page', 1))
    limit = int(request.query_params.get('limit', 10))
    paginator = Paginator(queryset, limit)
    vehicles_page = paginator.get_page(page)
    
    vehicles = []
    for vehicle in vehicles_page:
        vehicle_data = {
            'vehicle_id': vehicle.vehicle_id,
            'plate_number': vehicle.plate_number,
            'brand': vehicle.brand,
            'model': vehicle.model,
            'color': vehicle.color,
            'vehicle_type': vehicle.vehicle_type,
            'register_date': vehicle.register_date.strftime('%Y-%m-%d') if vehicle.register_date else None,
            'created_at': vehicle.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': vehicle.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }
        vehicles.append(vehicle_data)
    
    return Response({
        'code': 200,
        'message': '获取我的车辆列表成功',
        'data': {
            'count': paginator.count,
            'results': vehicles
        }
    })

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def add_my_vehicle(request):
    """
    为当前登录用户添加车辆
    """
    data = request.data
    try:
        # 检查必填字段
        if not data.get('plate_number') or not data.get('vehicle_type'):
            return Response({
                'code': 400, 
                'message': '车牌号和车辆类型为必填项'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 检查车牌号是否已存在
        if Vehicle.objects.filter(plate_number=data.get('plate_number')).exists():
            return Response({
                'code': 400,
                'message': '该车牌号已被绑定，请检查后重试'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 创建新车辆记录
        vehicle = Vehicle(
            plate_number=data.get('plate_number'),
            brand=data.get('brand'),
            model=data.get('model'),
            color=data.get('color'),
            vehicle_type=data.get('vehicle_type'),
            register_date=data.get('register_date') or timezone.now().date(),
            created_at=timezone.now(),
            updated_at=timezone.now()
        )
        
        # 绑定到当前用户
        vehicle.user = request.user
        
        vehicle.save()
        
        return Response({'code': 201, 'message': '添加车辆成功'}, status=status.HTTP_201_CREATED)
    except Exception as e:
        return Response({'code': 500, 'message': f'添加车辆失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET', 'PUT', 'DELETE'])
@permission_classes([IsAuthenticated])
def my_vehicle_detail(request, pk):
    """
    获取、更新或删除当前用户的单个车辆信息
    """
    try:
        # 只允许用户访问自己的车辆
        vehicle = Vehicle.objects.select_related('user').get(vehicle_id=pk, user=request.user)
    except Vehicle.DoesNotExist:
        return Response({'code': 404, 'message': '车辆不存在或您无权限操作'}, status=status.HTTP_404_NOT_FOUND)
    
    if request.method == 'GET':
        # 构建基本车辆信息
        vehicle_data = {
            'vehicle_id': vehicle.vehicle_id,
            'plate_number': vehicle.plate_number,
            'brand': vehicle.brand,
            'model': vehicle.model,
            'color': vehicle.color,
            'vehicle_type': vehicle.vehicle_type,
            'register_date': vehicle.register_date.strftime('%Y-%m-%d') if vehicle.register_date else None,
            'created_at': vehicle.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': vehicle.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }
        
        return Response({'code': 200, 'message': '获取车辆详情成功', 'data': vehicle_data})
    
    elif request.method == 'PUT':
        data = request.data
        try:
            # 检查车牌号是否已被其他车辆占用
            if data.get('plate_number') and data.get('plate_number') != vehicle.plate_number:
                if Vehicle.objects.filter(plate_number=data.get('plate_number')).exists():
                    return Response({
                        'code': 400,
                        'message': '该车牌号已被绑定，请检查后重试'
                    }, status=status.HTTP_400_BAD_REQUEST)
            
            # 更新基本信息
            vehicle.plate_number = data.get('plate_number', vehicle.plate_number)
            vehicle.brand = data.get('brand', vehicle.brand)
            vehicle.model = data.get('model', vehicle.model)
            vehicle.color = data.get('color', vehicle.color)
            vehicle.vehicle_type = data.get('vehicle_type', vehicle.vehicle_type)
            if data.get('register_date'):
                vehicle.register_date = data.get('register_date')
            vehicle.updated_at = timezone.now()
            
            vehicle.save()
            return Response({'code': 200, 'message': '更新车辆信息成功'})
        except Exception as e:
            return Response({'code': 500, 'message': f'更新车辆信息失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    elif request.method == 'DELETE':
        try:
            vehicle.delete()
            return Response({'code': 204, 'message': '删除车辆信息成功'}, status=status.HTTP_204_NO_CONTENT)
        except Exception as e:
            return Response({'code': 500, 'message': f'删除车辆信息失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def check_plate_number(request):
    """
    检查车牌号是否已被绑定
    """
    plate_number = request.query_params.get('plate_number', None)
    
    if not plate_number:
        return Response({
            'code': 400,
            'message': '请提供车牌号'
        }, status=status.HTTP_400_BAD_REQUEST)
    
    exists = Vehicle.objects.filter(plate_number=plate_number).exists()
    
    return Response({
        'code': 200,
        'message': '车牌号验证完成',
        'data': {
            'plate_number': plate_number,
            'is_available': not exists
        }
    })

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def vehicle_count(request):
    """
    获取当前用户的车辆数量
    """
    try:
        count = Vehicle.objects.filter(user=request.user).count()
        return Response({
            'code': 200,
            'message': '获取车辆数量成功',
            'data': {
                'count': count
            }
        })
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取车辆数量失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def available_devices(request):
    """
    获取正常状态的设备列表，用于维保申请
    只返回用户关联单元内的设备
    """
    try:
        # 获取当前用户
        user = request.user
        user_id = user.user_id
        
        # 从租赁申请表中查询用户关联的单元
        from services.models import LeasingApplicationService
        
        # 查询用户有效的租赁申请（已生效状态）
        leasing_applications = LeasingApplicationService.objects.filter(
            applicant_user_id=user_id,
            
        )
        
        if not leasing_applications.exists():
            # 如果没有有效的租赁申请，返回空列表
            return Response({
                'code': 200,
                'message': '未找到您关联的单元',
                'data': {
                    'total': 0,
                    'list': []
                }
            })
        
        # 获取用户关联的单元ID列表
        user_unit_ids = list(leasing_applications.values_list('unit_id', flat=True))
        
        # 获取查询参数
        device_type = request.query_params.get('device_type')
        building_id = request.query_params.get('building_id')
        
        # 基础查询 - 只获取状态正常的设备，并且只包含用户单元内的设备
        queryset = Device.objects.filter(
            status='正常',
            unit_id__in=user_unit_ids
        ).select_related('building', 'floor', 'unit')
        
        # 应用筛选条件
        if device_type:
            queryset = queryset.filter(device_type__icontains=device_type)
        if building_id:
            queryset = queryset.filter(building_id=building_id)
            
        # 按设备类型和名称排序
        queryset = queryset.order_by('device_type', 'device_name')
        
        # 序列化设备数据
        devices = []
        for device in queryset:
            location_parts = []
            if device.building:
                location_parts.append(device.building.name)
            if device.floor:
                location_parts.append(f"{device.floor.floor_number}层")
            if device.unit:
                unit_display_number = device.unit.unit_number.split('-')[-1]
                location_parts.append(unit_display_number)
            
            location_display = " - ".join(location_parts) if location_parts else device.location_desc
            
            devices.append({
                'device_id': device.device_id,
                'device_name': device.device_name,
                'device_number': device.device_number,
                'device_type': device.device_type,
                'location_desc': location_display,
                'unit_id': device.unit_id if device.unit else None
            })
        
        return Response({
            'code': 200,
            'message': '获取可用设备列表成功',
            'data': {
                'total': len(devices),
                'list': devices
            }
        })
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'获取设备列表失败: {str(e)}',
            'detail': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

# 添加获取用户真实姓名的函数
def _get_user_real_name(user: User):
    """
    获取用户的真实姓名，如果档案不存在则返回其用户名。
    """
    if not user:
        return None
    # 尝试从企业员工档案获取
    profile = CompanyEmployeeProfile.objects.filter(user=user).first()
    if profile:
        return profile.name
    # 其次从园区员工档案获取
    profile = ParkEmployeeProfile.objects.filter(user=user).first()
    if profile:
        return profile.name
    # 如果都没有，返回用户名
    return user.username


#获取房源列表

@api_view(['GET'])
def housing_query(request):
    """
    房源查询API
    支持按楼宇、楼层、单元类型、面积范围、价格范围、状态等条件筛选房源
    """
    # 获取查询参数
    building_id = request.query_params.get('building_id')
    floor_id = request.query_params.get('floor_id')
    unit_type = request.query_params.get('unit_type')
    status = request.query_params.get('status')
    min_area = request.query_params.get('min_area')
    max_area = request.query_params.get('max_area')
    min_price = request.query_params.get('min_price')
    max_price = request.query_params.get('max_price')
    page = int(request.query_params.get('page', 1))
    page_size = int(request.query_params.get('page_size', 10))

    # 构建查询条件
    query = Q()

    # 只查询可租赁的房源（状态为空置或者指定状态）
    if status:
        query &= Q(status=status)
    else:
        query &= Q(status='空置')

    # 按楼宇筛选
    if building_id:
        query &= Q(building_id=building_id)

    # 按楼层筛选
    if floor_id:
        query &= Q(floor_id=floor_id)

    # 按单元类型筛选
    if unit_type:
        query &= Q(unit_type=unit_type)

    # 按面积范围筛选
    if min_area:
        query &= Q(actual_area__gte=min_area)
    if max_area:
        query &= Q(actual_area__lte=max_area)

    # 按价格范围筛选
    if min_price:
        query &= Q(rental_price__gte=min_price)
    if max_price:
        query &= Q(rental_price__lte=max_price)

    # 执行查询
    units = Unit.objects.filter(query).select_related('building', 'floor')

    # 分页
    paginator = Paginator(units, page_size)
    units_page = paginator.get_page(page)

    # 构建响应数据
    units_data = []
    for unit in units_page:
        units_data.append({
            'unit_id': unit.unit_id,
            'unit_number': unit.unit_number,
            'unit_type': unit.unit_type,
            'status': unit.status,
            'actual_area': str(unit.actual_area) if unit.actual_area else '0.00',
            'building_area': str(unit.building_area) if unit.building_area else '0.00',
            'rental_price': str(unit.rental_price) if unit.rental_price else '0.00',
            'property_fee_standard': str(unit.property_fee_standard) if unit.property_fee_standard else '0.00',
            'orientation': unit.orientation,
            'facilities_desc': unit.facilities_desc,
            'media_urls': unit.media_urls,
            'building': {
                'building_id': unit.building.building_id,
                'name': unit.building.name
            },
            'floor': {
                'floor_id': unit.floor.floor_id if unit.floor else None,
                'floor_number': unit.floor.floor_number if unit.floor else None,
                'actual_label': unit.floor.actual_label if unit.floor else None
            } if unit.floor else None
        })

    # 获取筛选条件选项
    building_options = list(Building.objects.values('building_id', 'name'))
    floor_options = list(Floor.objects.values('floor_id', 'floor_number', 'actual_label'))
    unit_type_options = list(Unit.objects.values_list('unit_type', flat=True).distinct())
    status_options = list(Unit.objects.values_list('status', flat=True).distinct())

    return Response({
        'code': 200,
        'message': '获取房源列表成功',
        'data': {
            'total': paginator.count,
            'page': page,
            'page_size': page_size,
            'list': units_data,
            'filters': {
                'buildings': building_options,
                'floors': floor_options,
                'unit_types': unit_type_options,
                'statuses': status_options
            }
        }
    })